const db = require('../db');
const jwt = require('jsonwebtoken');
const { wx, jwtSecret, jwtExpire } = require('../config');

async function getOrderList(ctx) {
  let { page = 1, pageSize = 10, orderNo = '', status = '', nickname = '' } = ctx.query;
  page = parseInt(page);
  pageSize = parseInt(pageSize);

  // ✅ 获取并解析 token
  const token = ctx.headers.authorization?.replace('Bearer ', '');
  if (!token) {
    ctx.body = { code: 401, message: '请提供 token' };
    return;
  }

  let userId;
  try {
    const decoded = jwt.verify(token, jwtSecret);
    userId = decoded.userId;
  } catch (err) {
    console.log(err);
    
    ctx.body = { code: 401, message: 'token 无效或已过期' };
    return;
  }

  const where = ['user_id = ?']; // 只查当前用户的订单
  const params = [userId];

  if (orderNo) {
    where.push('order_no LIKE ?');
    params.push(`%${orderNo}%`);
  }
  if (status && status !== '全部') {
    where.push('status = ?');
    params.push(status);
  }
  if (nickname) {
    where.push('nickname LIKE ?');
    params.push(`%${nickname}%`);
  }

  const whereClause = `WHERE ${where.join(' AND ')}`;
  const totalSql = `SELECT COUNT(*) as count FROM orders ${whereClause}`;
  const [{ count }] = await db.query(totalSql, params);

  const offset = (page - 1) * pageSize;
  const listSql = `SELECT * FROM orders ${whereClause} ORDER BY created_at DESC LIMIT ?, ?`;
  const listParams = [...params, offset, pageSize];
  const list = await db.query(listSql, listParams);
  console.log(list);
  
  ctx.body = {
    code: 200,
    data: list[0],
    pagination: {
      total: count,
      current: page,
      pageSize
    }
  };
}

module.exports = {
  getOrderList
};
